package daniel.taotao.service.Impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import daniel.taotao.common.pojo.itemListPojo;
import daniel.taotao.common.utils.IDUtils;
import daniel.taotao.common.utils.TaotaoResult;
import daniel.taotao.mapper.TbItemDescMapper;
import daniel.taotao.mapper.TbItemMapper;
import daniel.taotao.pojo.TbItem;
import daniel.taotao.pojo.TbItemDesc;
import daniel.taotao.pojo.TbItemDescExample;
import daniel.taotao.pojo.TbItemDescExample.Criteria;
import daniel.taotao.pojo.TbItemExample;
import daniel.taotao.service.ItemService;
@Service
public class ItemServiceImpl implements ItemService {
	@Autowired
	private TbItemMapper itemMapper;
	
	@Autowired
	private JmsTemplate jmsTemplate;
	@Resource(name="itemAddtopic")
	private Destination destination;
	
	@Autowired 
	private TbItemDescMapper itemDescMapper;
	
	@Override
	public TbItem getItemById(Long id) {
		TbItem item = itemMapper.selectByPrimaryKey(id);
		return item;
	}

	@Override
	public itemListPojo getItemListPage(int page, int rows) {
		PageHelper.startPage(page, rows);
		TbItemExample example=new TbItemExample();
		List<TbItem> list = itemMapper.selectByExample(example);
		PageInfo<TbItem> pageInfo=new PageInfo<>(list);
		itemListPojo result=new itemListPojo();
		result.setRows(list);
		result.setTotal((int) pageInfo.getTotal());
		return result;
	}

	@Override
	public TaotaoResult addItem(TbItem item, String desc) {
		final Long id=IDUtils.genItemId();
		item.setId(id);
		item.setCreated(new Date());
		item.setUpdated(new Date());
		item.setStatus((byte) 1);
		itemMapper.insert(item);
		TbItemDesc itemDesc=new TbItemDesc();
		itemDesc.setItemId(id);
		itemDesc.setItemDesc(desc);
		itemDesc.setCreated(new Date());
		itemDesc.setUpdated(new Date());
		itemDescMapper.insert(itemDesc);
		jmsTemplate.send(destination,new MessageCreator() {
			
			@Override
			public Message createMessage(Session s) throws JMSException {
				TextMessage message = s.createTextMessage(id+"");
				System.out.println("发送通知--------------------");
				return message;
			}
		});
		
		return TaotaoResult.ok();
	}

	@Override
	public TbItemDesc getItemDescById(Long itemId) {
		TbItemDesc desc = itemDescMapper.selectByPrimaryKey(itemId);
		return desc;
	}

}
